import { Dimensions, PixelRatio, Platform } from 'react-native';

// 设计稿尺寸（基准尺寸）
const DESIGN_WIDTH = 375;
const DESIGN_HEIGHT = 812;

// 定义预设类型
type DevicePreset = {
  width: number;
  height: number;
  dpi: number;
};

type OrientationConfigs = {
  PORTRAIT?: DevicePreset[];
  LANDSCAPE?: DevicePreset[];
  DEFAULT: DevicePreset;
};

type DevicePresets = {
  PHONE: OrientationConfigs;
  TABLET: OrientationConfigs;
};

// 定义设备分辨率预设，设置用户实际设备为准确的基准
export const DEVICE_PRESETS: DevicePresets = {
  // 手机版预设
  PHONE: {
    // 竖屏配置 (手机模式)
    PORTRAIT: [
      { width: 540, height: 960, dpi: 240 },  // 添加当前设备配置
      { width: 450, height: 800, dpi: 200 },  // 添加当前设备配置
      { width: 360, height: 640, dpi: 160 }
    ],
    DEFAULT: { width: 450, height: 800, dpi: 200 } // 默认使用当前设备尺寸
  },

  // 平板版预设
  TABLET: {
    // 横屏配置 (平板模式) 
    LANDSCAPE: [
      { width: 1920, height: 1080, dpi: 280 },
      { width: 1600, height: 900, dpi: 240 },
      { width: 1280, height: 720, dpi: 240 },
      { width: 960, height: 540, dpi: 160 }
    ],
    DEFAULT: { width: 1920, height: 1080, dpi: 280 }
  }
};

// 获取屏幕尺寸
const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get('window');
const PIXEL_RATIO = PixelRatio.get();

// 平板判断阈值
const TABLET_WIDTH_THRESHOLD = 600;

// 判断设备类型
export const isTablet = (): boolean => {
  // 优先使用宽度判断
  if (SCREEN_WIDTH >= TABLET_WIDTH_THRESHOLD) return true;
  
  // 特殊设备兼容逻辑
  if (Platform.OS === 'ios') {
    // iOS特殊判断逻辑
    return Platform.isPad;
  }
  
  return false;
};

// 判断屏幕方向
export const isLandscape = (): boolean => {
  return SCREEN_WIDTH > SCREEN_HEIGHT;
};

// 获取最匹配的预设配置
export const getMatchingPreset = (): DevicePreset => {
  // 强制返回当前设备的实际尺寸作为预设
  // 这样可以保证在当前设备上的比例计算是精确的
  return {
    width: 450,
    height: 800, 
    dpi: 200
  };
};

// 获取当前最佳设计基准
export const getDesignBase = (): DevicePreset => {
  return getMatchingPreset();
};

// 响应式宽度计算 - 基于设计稿宽度的比例计算
export const wp = (designSize: number): number => {
  // 按照设计稿375的宽度比例计算
  return (designSize / DESIGN_WIDTH) * SCREEN_WIDTH;
};

// 响应式高度计算 - 基于设计稿高度的比例计算
export const hp = (designSize: number): number => {
  // 按照设计稿812的高度比例计算
  return (designSize / DESIGN_HEIGHT) * SCREEN_HEIGHT;
};

// 响应式尺寸计算 - 选择较小的缩放比例，避免字体过大
export const sp = (designSize: number): number => {
  const widthRatio = SCREEN_WIDTH / DESIGN_WIDTH;
  const heightRatio = SCREEN_HEIGHT / DESIGN_HEIGHT;
  // 取较小的缩放比例
  const ratio = Math.min(widthRatio, heightRatio);
  return designSize * ratio;
};

// 导出屏幕尺寸和像素密度
export const screenWidth = SCREEN_WIDTH;
export const screenHeight = SCREEN_HEIGHT;
export const pixelRatio = PIXEL_RATIO; 